package com.example.log4jdemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.slf4j.MDC;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@Slf4j
public class LogController {
    Logger logger = LogManager.getLogger(LogController.class);

    @RequestMapping(value = "/config", method = RequestMethod.GET)
    public String logConfig() {
        LoggerContext context = (LoggerContext) LogManager.getContext(false);
        System.out.println("context.getConfiguration().getName() = " + context.getConfiguration().getName());
        Map<String, LoggerConfig> loggers = context.getConfiguration().getLoggers();
        loggers.forEach((loggerName, logger) -> {
            System.out.println("loggerName = " + loggerName);
            logger.getAppenders().forEach((appenderName, appender) -> {
                System.out.println("appenderName = " + appenderName);
                if (appender instanceof RollingFileAppender rollingFileAppender) {
                    System.out.println("rollingFileAppender.getTriggeringPolicy() = " + rollingFileAppender.getTriggeringPolicy());
                    System.out.println("rollingFileAppender.getManager().getRolloverStrategy() = " + rollingFileAppender.getManager().getRolloverStrategy());
                    System.out.println("rollingFileAppender.getFileName() = " + rollingFileAppender.getFileName());
                }
            });
        });
        logger.info("abc");
        return "success";
    }

    @RequestMapping(value = "/log/{count}", method = RequestMethod.GET)
    public String log(@PathVariable("count") String count) {
        mdc();
        printlog(Integer.parseInt(count));

        return "success";
    }

    private void printlog(int count) {
        for (int i = 0; i < count; i++) {
            log.info("count=" + count);
        }
    }

    private static void mdc() {
        // log4j写法
//        Map<String, String> context = ThreadContext.getContext();
//        context.put("user", "guest");
        // slf4j日志门面写法
        MDC.put("user", "guest");
    }
}
